package problem.year2021.february;

/**
 * 给定一个由若干 0 和 1 组成的数组 A，我们最多可以将 K 个值从 0 变成 1 。
 * 返回仅包含 1 的最长（连续）子数组的长度。
 * 示例 1：
 * 输入：A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
 * 输出：6
 * 解释：
 * [1,1,1,0,0,1,1,1,1,1,1]
 * 粗体数字从 0 翻转到 1，最长的子数组长度为 6。
 * 示例 2：
 * 输入：A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
 * 输出：10
 * 解释：
 * [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
 * 粗体数字从 0 翻转到 1，最长的子数组长度为 10。
 * 提示：
 * 1 <= A.length <= 20000
 * 0 <= K <= A.length
 * A[i] 为 0 或 1
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/max-consecutive-ones-iii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class February19 {
    public int longestOnes(int[] A, int K) {
        if (K == 0) {
            int len = 0;
            int len1 = 0;
            for (int i : A) {
                if (i == 1) {
                    len1++;
                } else {
                    len = Math.max(len, len1);
                    len1 = 0;
                }
            }
            len = Math.max(len, len1);
            return len;
        }
        int n = A.length;
        int p = 0;
        int left = 0, right = 0;
        int sum = 0;
        while (left <= right && right < n) {
            if (A[right] == 0) {
                if (p < K) {
                    right++;
                    sum = Math.max(sum, right - left);
                    p++;
                } else {
                    if (A[left] == 0) {
                        p--;
                        left++;
                    } else {
                        left++;
                    }
                }
            } else {
                right++;
                sum = Math.max(sum, right - left);
            }
        }
        return sum;
    }
    public int longestOnes2(int[] A, int K) {
        int n = A.length;
        int left = 0, lsum = 0, rsum = 0;
        int ans = 0;
        for (int right = 0; right < n; ++right) {
            rsum += 1 - A[right];
            while (lsum < rsum - K) {
                lsum += 1 - A[left];
                ++left;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }

    public static void main(String[] args) {
        //  输入：A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3, answer = 10
        int[] A = new int[]{0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1};
        int[] A1 = new int[]{1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0};
        int[] A2 = new int[]{1, 1, 1, 0, 0, 0, 1, 1, 1, 1};
        System.out.println(new February19().longestOnes(A, 3));
        System.out.println(new February19().longestOnes(A1, 2));
        System.out.println(new February19().longestOnes(A2, 0));
    }
}
